﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js深拷贝实现</title>
</head>
<body>
<script type="text/javascript">
    function type (arg) {
        var type = Object.prototype.toString.call(arg)
        var flag = type.replace('[', '').replace(']', '').split(' ')[ 1 ]
        return {
            [ 'is' + flag ]: true
        }
    }
    // 参数，要拷贝的对象，要设置进去的对象
    function deepCopy (arg) {
        var result = null
        if (type(arg).isArray) {
            result = []
            for (var i = 0; i < arg.length; i++) {
                result.push(deepCopy(arg[i]))
            }
        } else if (type(arg).isObject) {
            result = {}
            for (var key in arg) {
                result[ key ] = deepCopy(arg[ key ])
            }
        } else {
            result = arg
        }
        return result
    }


    var res = deepCopy({
        hp: {
            name: {
                big: 'xx',
                ff: 'xxds'
            },
            sdsd: {
                dfdf: 'xxx',
                dsdssd: {
                    trtrt: 'x'
                }
            },
            dsds: 'xx'
        },
        arr: [1, 1, 1, 1, 1]
    })
    console.log(res)
</script>
</body>
</html>